package com.kaikai.edu.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaikai.commonutils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.binding.BinderAwareChannelResolver;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;



@Component
public class MsgSender {

    @Autowired
    private BinderAwareChannelResolver resolver;

    /**
     * @param message
	 * @param topic
     * @return void
     * @Author yujiankai
     * @Description 向消息队列发送消息
     * @date 2022/1/6 15:21
     */
    public <T> void sendMessage(T message, String topic) throws JsonProcessingException {
        String sendStr;
        if (message instanceof String) {
            sendStr = message.toString();
        } else {
            //将传入的对象序列化位json
            sendStr = JsonUtil.convertObjectToJson(message);
        }
        resolver.resolveDestination(topic)
                .send(new GenericMessage<>(sendStr.getBytes(StandardCharsets.UTF_8)));
    }


}
